import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
//导入axios
import { getUserInfoAPI } from '@/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    //存储登陆成功后得到的token
    token: '', //保存token字符串
    userInfo: {} //保存用户信息（id,username,email,user_pic）
  },
  mutations: { //同步函数 利用$store.commit调用
    //更新token的mutation函数
    updateToken(state, newToken) {
      state.token = newToken
    },
    //跟新用户信息
    updateUserInfo(state, info) {
      state.userInfo = info
    }
  },

  actions: { //封装异步  利用$store.didispatch调用
    //定义初始化用户基本信息的action函数
    async initUserInfo(store) {
      const { data: res } = await getUserInfoAPI()

      if (res.code === 0) {
        store.commit('updateUserInfo', res.data)
        console.log(res, '333');
      }
      console.log(res, '343');
    }
  },
  getters: {
    //完整写法
    // username(state){
    //   return state.userInfo.username
    // }
    nickname: state => state.userInfo.nickname,
    username: state => state.userInfo.username,
    user_pic: state => state.userInfo.user_pic
  },
  //配置vuex插件
  plugins: [createPersistedState()],
  modules: {
  }
})
